package xworker.lang.util.codeassist.variableproviders;

import org.xmeta.ActionContext;
import org.xmeta.Thing;
import org.xmeta.World;
import xworker.lang.VariableDesc;
import xworker.lang.util.codeassist.VariableProvider;

import java.util.ArrayList;
import java.util.List;

public class ImportClassProvider implements VariableProvider {

	@Override
	public List<VariableDesc> getVariables(String code, int offset, List<String> statements, Thing thing,
			ActionContext actionContext) {
		if(code == null || "".equals(code)) {
			return null;
		}
		
		List<VariableDesc> vars = new ArrayList<>();
		for(String line : code.split("[\n]")) {
			line = line.trim();
			if(line.startsWith("import ")) {
				int lastIndex = line.lastIndexOf(";");
				String className = line.substring(6, lastIndex).trim();
				int index = className.lastIndexOf(".");			
				String name = index == -1 ? className : className.substring(index + 1);
				
				vars.add(new VariableDesc(name, VariableDesc.OBJECT, className, null));
			}else if(line.contains("//def ")){
				int index = line.indexOf("//def ");
				line = line.substring(index + 6).trim();
				String[] ls = line.split("[:]");
				if(ls.length == 2){
					vars.add(new VariableDesc(ls[0].trim(), VariableDesc.OBJECT, ls[1].trim(), null));
				}else if(ls.length == 3){
					vars.add(new VariableDesc(ls[0].trim(), ls[1].trim(), ls[2].trim(), null));
				}else if(ls.length > 3){
					Thing varThing = World.getInstance().getThing(ls[3].trim());
					vars.add(new VariableDesc(ls[0].trim(), ls[1].trim(), ls[2].trim(), varThing));
				}
			}
		}
		
		return vars;
	}

}
